package com.csii.user.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.csii.user.entity.SysUser;
import com.csii.user.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

//@Component
public class RedisPublishService {

    @PostConstruct
    private void init(){
        userSyncRedis();
    }

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SysUserMapper userMapper;

    private final String AUTH_USER_ALL_VERSION = "AUTH_USER_ALL_VERSION";

    private final String AUTH_USER_ALL = "AUTH_USER_ALL";

    @Async
    public void userSyncRedis(){
        String version = (String) redisTemplate.opsForValue().get(AUTH_USER_ALL_VERSION);

        if ("1".equals(version)){
            return;
        }

        if (version == null){
            version = "1";
        }
        List<SysUser> sysUserList = userMapper.selectList(new LambdaQueryWrapper<SysUser>().eq(SysUser::getStatus,1).eq(SysUser::getDelFlag,0));

        String userListJson = JSONUtil.toJsonStr(sysUserList);
        redisTemplate.opsForValue().set(AUTH_USER_ALL,userListJson);
        redisTemplate.opsForValue().set(AUTH_USER_ALL_VERSION, String.valueOf(Integer.valueOf(version)+1));
    }



}
